package com.ease.kaola;

import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.net.Socket;

/**
 * RESP (REdis Serialization Protocol)协议
 *
 * 仿造Jedis客户端，通过手写redis java客户端，看透底层优化细节
 * 常见于RPC框架，Zookeeper, dubbo, MQ ...
 *
 * 1.组装请求数据包
 * 2.发送请求数据到Redis服务器 --- 通过tcp连接
 * 3.获取Redis返回
 *
 * @author: chenhs
 * @date: Created in 6:44 2019/11/12
 **/
public class TonyRedisClient {

    Socket connection;

    public TonyRedisClient(String host, int port) throws IOException {
        this.connection = new Socket(host, port);
    }


    public String get(String key) throws IOException {

        //1.组装请求数据包
        StringBuilder request = new StringBuilder();
        //请求分两部分
        request.append("*2").append("\r\n");
        //第一个参数长度
        request.append("$3").append("\r\n");
        //第一个参数的值
        request.append("GET").append("\r\n");
        //第N个参数长度
        request.append("$").append(key.getBytes().length).append("\r\n");
        //第N个参数的值
        request.append(key).append("\r\n");

        System.out.println("redis请求协议内容：");
        System.out.println(request.toString());

        connection.getOutputStream().write(request.toString().getBytes());
        byte[] response = new byte[1024];
        connection.getInputStream().read(response);

        return new String(response);
    }

    //普通模式
    public String set(String key, String value) throws IOException {

        //1.组装请求数据包
        StringBuilder request = new StringBuilder();
        //请求分两部分
        request.append("*3").append("\r\n");
        //第一个参数长度
        request.append("$3").append("\r\n");
        //第一个参数的值
        request.append("SET").append("\r\n");

        request.append("$").append(key.getBytes().length).append("\r\n");
        request.append(key).append("\r\n");

        request.append("$").append(value.getBytes().length).append("\r\n");
        request.append(value).append("\r\n");

        connection.getOutputStream().write(request.toString().getBytes());
        byte[] response = new byte[1024];
        connection.getInputStream().read(response);

        return new String(response);
    }



    public static void main(String[] args) throws IOException {
        /*
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String s = jedis.get("hello");
        System.out.println(s);*/

/*
        TonyRedisClient tonyRedisClient = new TonyRedisClient("127.0.0.1", 6379);
        String hello = tonyRedisClient.get("hello");
        System.out.println(hello);*/



        TonyRedisClient tonyRedisClient = new TonyRedisClient("127.0.0.1", 6379);
        long t = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            tonyRedisClient.set("hello", String.valueOf(i));
        }
        System.out.println(System.currentTimeMillis()-t);





    }

}
